package cn.kwq.project_manger.service.impl;

import cn.kwq.project_manger.pojo.dto.WYU_Dto;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 联通教务系统信息
 */
@Component
@Slf4j
public class LoginWyuSystemImpl {

    @Value("${WYU.WYU_URL}")
    private String WYU_URL;
    @Value("${WYU.REFERER}")
    private String REFERER;

    /**
     * WYU系统登录获取信息
     *
     * @param token
     * @return WYU_Dto
     */
    public WYU_Dto getMessageByWYUsys(String token) throws IOException, ParseException {

        Document doc = Jsoup.connect(WYU_URL)
                .header("Cookie",token)
                .header("Referer",REFERER)
                .post();


        return doFilterMsg(doc);


    }

    /**
     * 解析需要的数据
     * @param doc html对象
     * @return 清洗后得数据封装对象
     */
    private WYU_Dto doFilterMsg(Document doc) throws ParseException {



        Element div = doc.getElementsByClass("easyui-panel").first();
        Element table = div.getElementsByTag("table").first();
        Elements trs = table.getElementsByTag("tr");

        Element tr1 = trs.select("tr").get(0);
        Element tr2 = trs.select("tr").get(1);
        Element tr3 = trs.select("tr").get(2);

        String stuNum = tr1.select("label").get(0).text();
        String name = tr1.select("label").get(1).text();
       String year = tr1.select("label").get(2).text();

        String institute = tr2.select("label").get(0).text();
        String major = tr2.select("label").get(1).text();


        String WYUclass = tr3.select("label").get(0).text();
        String grade = tr3.select("label").get(1).text();


       Date enterYear= String2Date(year);


       return WYU_Dto
               .builder()
               .stuNum(stuNum)
               .name(name)
               .year(enterYear)
               .institute(institute)
               .major(major)
               .WYUclass(WYUclass)
               .grade(grade)
               .build();
    }

    /**
     * 字符串转年
     * @param year
     * @return
     * @throws ParseException
     */
    private Date String2Date(String year) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        Date date = formatter.parse(year);
        return date;
    }
}
